<template>
	<div class="user-list">
		<div style="margin: 20px 0">
			<el-button type="primary" @click="addShop">添加商品分组</el-button>
		</div>
		<el-table :data="shops" style="width: 100%">
			<el-table-column prop="id" label="ID" min-width="80" />
			<el-table-column prop="name" label="商品分组名称" min-width="120" />
			<el-table-column prop="typeId" label="商品分组类别" min-width="120">
				<template #default="scope">
					<el-tag type="danger" effect="dark">
						{{ scope.row.type.name }}
					</el-tag>
				</template>
			</el-table-column>
			<el-table-column
				prop="position"
				label="商品分组位置"
				min-width="120"
			/>
			<el-table-column prop="shopType" label="产品分类" min-width="180">
				<template #default="scope">
					<div
						v-for="item in scope.row.shop_types"
						:key="item.id"
						style="margin: 8px; display: flex; align-item: center"
					>
						<el-tag type="warning">
							{{ item.name }}
						</el-tag>
						<span
							style="
								font-size: 14px;
								padding: 0 10px;
								color: red;
								cursor: pointer;
							"
							@click="handleDelShopType(item.id)"
							>删除</span
						>
					</div>
				</template>
			</el-table-column>
			<!-- <el-table-column prop="desc" label="商品分组简介" min-width="120" /> -->
			<el-table-column prop="logo" label="商品分组logo" min-width="160">
				<template #default="scope">
					<img
						v-if="scope.row.logo"
						:src="'http://localhost:3000/' + scope.row.logo"
						alt=""
						style="width: 120px; height: 120px"
					/>
					<el-tag v-else type="danger">暂未上传logo</el-tag>
				</template>
			</el-table-column>
			<el-table-column prop="cover" label="商品分组封面" min-width="240">
				<template #default="scope">
					<img
						v-if="scope.row.cover"
						:src="'http://localhost:3000/' + scope.row.cover"
						alt=""
						style="width: 200px; height: 200px"
					/>
					<el-tag v-else type="danger">暂未上传封面</el-tag>
				</template>
			</el-table-column>
			<el-table-column label="操作" min-width="500">
				<template #default="scope">
					<el-button
						type="primary"
						@click="handleUploadLogo(scope.row)"
						>上传logo</el-button
					>
					<el-button
						type="primary"
						@click="handleUploadCover(scope.row)"
						>上传封面</el-button
					>
					<el-button
						type="primary"
						@click="handleOpenShopType(scope.row)"
						>添加产品分类</el-button
					>
					<el-button type="warning" @click="updateShop(scope.row)"
						>编辑</el-button
					>
					<el-button type="danger" @click="delShop(scope.row)"
						>删除</el-button
					>
				</template>
			</el-table-column>
		</el-table>

		<el-dialog
			v-model="dialogInfo.visible"
			:title="dialogInfo.title"
			width="50%"
			:close-on-click-modal="false"
			:destroy-on-close="true"
		>
			<el-form
				ref="ruleFormRef"
				:model="form"
				:rules="rules"
				label-width="80px"
			>
				<el-form-item label="商品分组名称" prop="name">
					<el-input v-model="form.name" />
				</el-form-item>
				<el-form-item label="商品分组简介" prop="desc">
					<div style="border: 1px solid #ccc; height: 500px">
						<Toolbar
							style="border-bottom: 1px solid #ccc"
							:editor="editorRef"
							:defaultConfig="toolbarConfig"
							mode="simple"
						/>
						<Editor
							style="height: 360px; overflow-y: hidden"
							v-model="form.desc"
							:defaultConfig="editorConfig"
							mode="simple"
							@onCreated="handleCreated"
						/>
					</div>
				</el-form-item>
				<el-form-item label="商品分组类型" prop="typeId">
					<el-select
						v-model="form.typeId"
						class="m-2"
						placeholder="请选择类型"
					>
						<el-option
							v-for="item in types"
							:key="item.id"
							:label="item.name"
							:value="item.id"
						/>
					</el-select>
				</el-form-item>
				<el-form-item
					label="商品分组位置"
					prop="position"
					v-if="!dialogInfo.type"
				>
					<div id="container"></div>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="submitForm(ruleFormRef)"
						>确定
					</el-button>
					<el-button @click="resetForm(ruleFormRef)">取消</el-button>
				</el-form-item>
			</el-form>
		</el-dialog>

		<el-dialog
			v-model="uploadLogoDialog.visible"
			title="上传logo"
			width="30%"
			:close-on-click-modal="false"
			:destroy-on-close="true"
		>
			<el-upload
				:action="
					'http://localhost:3000/api/shop/upload/logo?id=' +
					uploadLogoDialog.uploadData.id
				"
				:data="uploadLogoDialog.uploadData"
				:limit="1"
				list-type="picture-card"
				:on-success="handleUploadLogoSuccess"
			>
				<el-icon>
					<Plus />
				</el-icon>
			</el-upload>
		</el-dialog>

		<el-dialog
			v-model="uploadCoverDialog.visible"
			title="上传封面"
			width="30%"
			:close-on-click-modal="false"
			:destroy-on-close="true"
		>
			<el-upload
				:action="
					'http://localhost:3000/api/shop/upload/cover?id=' +
					uploadCoverDialog.uploadData.id
				"
				:data="uploadCoverDialog.uploadData"
				list-type="picture-card"
				:limit="1"
				:on-success="handleUploadCoverSuccess"
			>
				<el-icon>
					<Plus />
				</el-icon>
			</el-upload>
		</el-dialog>

		<el-dialog
			v-model="shopTypeDialogInfo.visible"
			:title="shopTypeDialogInfo.title"
			width="40%"
			:close-on-click-modal="false"
			:destroy-on-close="true"
		>
			<el-form :model="shopTypeDialogInfo.form" label-width="80px">
				<el-form-item label="分类名称" prop="name">
					<el-input v-model="shopTypeDialogInfo.form.name" />
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAddShopType"
						>确定
					</el-button>
				</el-form-item>
			</el-form>
		</el-dialog>
	</div>
</template>

<script setup>
import { onBeforeUnmount, onMounted, reactive, ref, shallowRef } from "vue";
import { list } from "@/api/types";
import {
	add,
	del,
	list as shopList,
	update,
	addShopType,
	delShopType,
} from "@/api/shop";

import { ElMessage } from "element-plus";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";

const editorRef = shallowRef();
const ruleFormRef = ref();

const toolbarConfig = {};
const editorConfig = { placeholder: "请输入简介..." };
const types = ref([]);
const shops = ref([]);
const dialogInfo = reactive({
	title: "添加商品分组类型",
	visible: false,
	type: 0,
});

const shopTypeDialogInfo = reactive({
	title: "添加产品类型",
	visible: false,
	type: 0,
	form: {
		id: "",
		name: "",
		shopId: "",
	},
});

const uploadLogoDialog = reactive({
	visible: false,
	uploadData: {
		id: 0,
	},
});

const uploadCoverDialog = reactive({
	visible: false,
	uploadData: {
		id: 0,
	},
});

const state = reactive({
	marker: [],
	current_position: [],
});
const form = reactive({
	name: "",
	desc: "",
	lng: "",
	lat: "",
	position: "",
	typeId: "",
	id: 0,
});

const rules = reactive({
	name: [{ required: true, message: "请输入商品分组名称", trigger: "blur" }],
	desc: [{ required: true, message: "请输入商品分组简介", trigger: "blur" }],
	lng: [{ required: true, message: "请选择商品分组地址", trigger: "blur" }],
	lat: [{ required: true, message: "请选择商品分组地址", trigger: "blur" }],
	position: [
		{ required: true, message: "请输入商品分组具体位置", trigger: "blur" },
	],
	typeId: [
		{ required: true, message: "请选择商品分组类型", trigger: "blur" },
	],
});

onMounted(() => {
	getType();
	getShops();
});

const handleCreated = editor => {
	editorRef.value = editor; // 记录 editor 实例，重要！
};

const getType = async () => {
	try {
		const res = await list();
		types.value = res.result;
	} catch (err) {
		console.error(err);
	}
};

const getShops = async () => {
	try {
		const res = await shopList();
		shops.value = res.result;
	} catch (err) {
		console.error(err);
	}
};

const addShop = () => {
	form.id = "";
	form.name = "";
	form.desc = "";
	form.lng = "";
	form.lat = "";
	form.position = "";
	form.typeId = "";
	dialogInfo.type = 0;
	dialogInfo.title = "添加商品分组类型";
	dialogInfo.visible = true;
	setTimeout(() => {
		initMap();
	}, 1000);
};

const updateShop = row => {
	form.id = row.id;
	form.name = row.name;
	form.typeId = row.typeId;
	form.lat = row.lat;
	form.lng = row.lng;
	form.desc = row.desc;
	form.position = row.position;
	dialogInfo.type = 1;
	dialogInfo.title = "修改商品分组类型";
	dialogInfo.visible = true;
};

const submitForm = async formEl => {
	if (!formEl) return;
	await formEl.validate(async (valid, fields) => {
		if (valid) {
			if (form.desc.length > 80) {
				ElMessage.error("简介长度不大于80");
				return;
			}
			if (!dialogInfo.type) {
				await add({
					name: form.name,
					desc: form.desc,
					lng: form.lng,
					lat: form.lat,
					position: form.position,
					typeId: form.typeId,
				});
				ElMessage.success("添加成功");
				resetForm(ruleFormRef.value);
				getShops();
				return;
			}

			await update(form);
			ElMessage.success("修改成功");
			resetForm(ruleFormRef.value);
			getShops();
		}
	});
};

const delShop = async row => {
	await del({
		id: row.id,
	});
	ElMessage.success("删除成功");
	getShops();
};

const handleUploadLogo = row => {
	uploadLogoDialog.uploadData.id = row.id;
	uploadLogoDialog.visible = true;
};

const handleUploadLogoSuccess = () => {
	uploadLogoDialog.visible = false;
	ElMessage.success("上传成功");
	getShops();
};

const handleUploadCover = row => {
	uploadCoverDialog.uploadData.id = row.id;
	uploadCoverDialog.visible = true;
};

const handleUploadCoverSuccess = () => {
	uploadCoverDialog.visible = false;
	ElMessage.success("上传成功");
	getShops();
};

const handleOpenShopType = row => {
	shopTypeDialogInfo.form.shopId = row.id;
	shopTypeDialogInfo.visible = true;
};

const handleAddShopType = async () => {
	if (!shopTypeDialogInfo.form.name) {
		ElMessage.error("类型名称不允许为空");
		return;
	}
	await addShopType({
		name: shopTypeDialogInfo.form.name,
		shopId: shopTypeDialogInfo.form.shopId,
	});
	ElMessage.success("添加成功");
	shopTypeDialogInfo.form.name = "";
	shopTypeDialogInfo.visible = false;
	getShops();
};

const handleDelShopType = async id => {
	await delShopType({ id });
	ElMessage.success("删除成功");
	getShops();
};

const resetForm = formEl => {
	if (!formEl) return;
	formEl.resetFields();
	dialogInfo.visible = false;
};

//进行地图初始化
const initMap = () => {
	const map = new AMap.Map("container", {
		//设置地图容器id
		viewMode: "3D", //是否为3D地图模式
		zoom: 10, //初始化地图级别
		center: [120.374926, 30.310678], //初始化地图中心点位置
	});
	//添加插件
	AMap.plugin(
		["AMap.ToolBar", "AMap.Scale", "AMap.HawkEye", "AMap.Geolocation"],
		function () {
			//异步同时加载多个插件
			map.addControl(new AMap.HawkEye()); //显示缩略图
			map.addControl(new AMap.Scale()); //显示当前地图中心的比例尺
		}
	);
	// 单击
	map.on("click", e => {
		const lat = Number(e.lnglat.lat.toFixed(5));
		const lng = Number(e.lnglat.lng.toFixed(5));
		state.current_position = [lng, lat];
		AMap.plugin("AMap.Geocoder", () => {
			const geocoder = new AMap.Geocoder({ city: "全国" });

			geocoder.getAddress(state.current_position, (status, result) => {
				if (status === "complete" && result.info === "OK") {
					form.position = result.regeocode.formattedAddress;
					form.lat = lat;
					form.lng = lng;
				}
			});
		});
		addMarker();
	});

	// 实例化点标记
	function addMarker() {
		if (state.marker.length) {
			map.remove(state.marker[0]);
			state.marker.pop();
		}
		const marker = new AMap.Marker({
			icon: "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
			position: state.current_position,
			offset: new AMap.Pixel(-26, -54),
		});
		state.marker.push(marker);
		marker.setMap(map);
	}
};

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
	const editor = editorRef.value;
	if (editor == null) return;
	editor.destroy();
});
</script>
<style scoped>
.avatar-uploader .avatar {
	width: 178px;
	height: 178px;
	display: block;
}

#container {
	padding: 0px;
	margin: 0px;
	width: 100%;
	height: 800px;
}
</style>

<style>
.avatar-uploader .el-upload {
	border: 1px dashed var(--el-border-color);
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
	transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
	border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 178px;
	height: 178px;
	text-align: center;
}
</style>
